package org.jbfilter.demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.jbfilter.impl.HibernateCallback;
import org.jbfilter.impl.HibernateTemplate;
import org.jbfilter.test.beans.Composer;
import org.jbfilter.test.beans.factory.ComposerFactory;

/**
 * Startup Hibernate and provide access to the singleton SessionFactory
 */
public class HibernateUtil {

  private static SessionFactory sessionFactory;
  private static HibernateTemplate template;

  static {
    try {
       sessionFactory = getConf().buildSessionFactory();
       template = new HibernateTemplate(sessionFactory);
    } catch (Throwable ex) {
       throw new ExceptionInInitializerError(ex);
    }
  }

  public static SessionFactory getSessionFactory() {
      // Alternatively, we could look up in JNDI here
      return sessionFactory;
  }

  public static void shutdown() {
      // Close caches and connection pools
      getSessionFactory().close();
  }
  
  public static void buildDB() {
	  SchemaExport schemaExport = new SchemaExport(getConf());
	  schemaExport.create(true, true);
	  template.execute(new HibernateCallback<Object>() {
		public Object doInHibernate(Session session) {
			for (Composer composer : ComposerFactory.getInstance().getAll()) {
				session.saveOrUpdate(composer);	
			}
			return null;
		}
	  });
	  
  }
  
  private static AnnotationConfiguration getConf() {
	  AnnotationConfiguration annConf = new AnnotationConfiguration().configure();
	  annConf.addAnnotatedClass(Composer.class);
	  return annConf;
  }
}